package api

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"strings"
	"sync"
	"wwgin/global/variable"
	"wwgin/module/response"
	"wwgin/service"
	"wwgin/validate/api/ip"
)

type Ip struct{}

//获取一个ip地址的信息
func (u *Ip) GetInfo(c *gin.Context) {
	//参数绑定验证
	var requestIp = ip.IpFind{}
	err := c.ShouldBind(&requestIp) //参数绑定
	if err != nil {
		for _, err := range err.(validator.ValidationErrors) {
			response.Fail(c, err.Translate(variable.Trans)) // validator.ValidationErrors类型错误则进行翻译
			return
		}
	}

	ipService := service.IpService{}
	one, err := ipService.GetOne(requestIp.Ip)
	if err != nil {
		response.Fail(c, err.Error())
		return
	}
	response.SuccessData(c, "成功", one)
}

//获取多个ip地址的信息,多个使用英文逗号分隔 - 使用协程并发查询
func (u *Ip) GetInfos(c *gin.Context) {
	ips := c.DefaultQuery("ip", "")
	if ips == "" {
		response.Fail(c,"ip地址不能为空")
		return
	}
	group := sync.WaitGroup{}
	var list = []map[string]interface{}{}
	for _, i := range strings.Split(ips, ",") {
		ipService := service.IpService{}
		group.Add(1)
		go func(ip_s string) {
			one, e := ipService.GetOne(ip_s)
			if e == nil {
				list = append(list, one)
			}
			group.Done()
		}(i)
	}
	group.Wait()
	response.SuccessData(c, "成功", list)
}
